import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录', noAuth: true },
    },
    {
      path: '/',
      component: () => import('@/layouts/MainLayout.vue'),
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '首页' },
        },
        {
          path: 'workflow',
          name: 'Workflow',
          meta: { title: '流程任务' },
          children: [
            {
              path: 'todo',
              name: 'TodoList',
              component: () => import('@/views/workflow/TodoList.vue'),
              meta: { title: '待办任务' },
            },
            {
              path: 'done',
              name: 'DoneList',
              component: () => import('@/views/workflow/DoneList.vue'),
              meta: { title: '已办任务' },
            },
          ],
        },
        {
          path: 'process',
          name: 'Process',
          meta: { title: '流程管理' },
          children: [
            {
              path: 'design',
              name: 'ProcessDesign',
              component: () => import('@/views/process/ProcessDesign.vue'),
              meta: { title: '流程设计' },
            },
            {
              path: 'design/editor',
              name: 'ProcessEditor',
              component: () => import('@/views/ProcessDesign.vue'),
              meta: { title: '流程设计器' },
            },
            {
              path: 'instance',
              name: 'ProcessInstance',
              component: () => import('@/views/process/Instance.vue'),
              meta: { title: '流程实例' },
            },
          ],
        },
        {
          path: 'system',
          name: 'System',
          meta: { title: '系统管理' },
          children: [
            {
              path: 'menu',
              name: 'MenuManagement',
              component: () => import('@/views/system/Menu.vue'),
              meta: { title: '菜单管理' },
            },
            {
              path: 'dict',
              name: 'DictManagement',
              component: () => import('@/views/system/Dict.vue'),
              meta: { title: '字典管理' },
            },
            {
              path: 'tenant',
              name: 'TenantManagement',
              component: () => import('@/views/system/Tenant.vue'),
              meta: { title: '租户管理' },
            },
          ],
        },
      ],
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token

  // 设置页面标题
  document.title = `${to.meta.title || '工作流平台'}`

  if (to.meta.noAuth) {
    // 不需要登录的页面
    if (token && to.path === '/login') {
      // 已登录时访问登录页，跳转到上次退出时的页面或首页
      const redirect = userStore.lastPath || '/'
      next(redirect)
    } else {
      next()
    }
  } else {
    // 需要登录的页面
    if (!token) {
      // 未登录，保存当前路径并重定向到登录页
      if (to.path !== '/') {
        userStore.setLastPath(to.fullPath)
      }
      next({
        path: '/login',
      })
    } else {
      try {
        // 验证token是否有效
        await getUserInfo()
        next()
      } catch (error) {
        // token无效，清除用户状态并跳转到登录页
        userStore.clear()
        ElMessage.error('登录已过期，请重新登录')
        next({
          path: '/login',
          query: { redirect: to.fullPath },
        })
      }
    }
  }
})

export default router
